package com.domain.cumanager;

import org.apache.log4j.Logger;

import com.domain.Task;
import com.domain.TasksArray;
import com.domain.exceptions.FailedToDispatchPlans;
import com.domain.exceptions.FailedToDispatchTask;
import com.domain.exceptions.NotFoundAvailableCU;

public class CUManager {
	private CUStubsHolder m_cuStubsHolder;
	private CURegistrator m_cuRegistrator;
	private static Logger s_logger;
	

	public CUManager(){
		s_logger = Logger.getLogger(CUManager.class);
		m_cuStubsHolder = new CUStubsHolder();
		m_cuRegistrator = new CURegistrator(m_cuStubsHolder);
		m_cuRegistrator.start();
		
	}

	public void dispatchPlans(TasksArray tasksArray) throws FailedToDispatchPlans{
		s_logger.info("Begins plans dispatch process. plan id :" + tasksArray.getId());
		try {			
			for(int i = 0; i < tasksArray.size(); i++){
				Task task = tasksArray.getTask(i);
				CUStub cuStub = m_cuStubsHolder.getAvailableCU();
				cuStub.addTask(task);
			}
		} 
		catch (NotFoundAvailableCU e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			s_logger.warn("Not found available CU for tasksArray. id :" + tasksArray.getId());
			throw new FailedToDispatchPlans();
		} 
		catch (FailedToDispatchTask e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			s_logger.warn("Failed to dispatch task. tasksArray.id :" + tasksArray.getId());
			throw new FailedToDispatchPlans();			
		}
		s_logger.info("ends plans dispatch process ok. plan id :" + tasksArray.getId());
	}


}
